package com.xialj.demoend.controller;

import cn.hutool.core.util.CharsetUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.google.common.collect.Maps;
import com.xialj.demoend.common.Result;
import com.xialj.demoend.common.ResultCodeEnum;
import com.xialj.demoend.entity.User;
import com.xialj.demoend.entity.UserExport;
import com.xialj.demoend.service.UserService;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Sheet;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

/**
 * @Author xlj
 * @Date Created in  2023/2/23 17:25
 * @DESCRIPTION:
 * @Version V1.0
 */
@RestController
@SuppressWarnings("all")
@RequestMapping("/user/message")
@Slf4j
@CrossOrigin
public class UserController {

    @Resource
    private UserService userService;

    @ApiOperation("查询所有用户信息")
    @PostMapping("/allUserMessage")
    public Result selectAllUser(@RequestBody User user) {
        Result userList = userService.allUserMessage(user);
        log.info("{}", userList);
        return userList;
    }
    @ApiOperation("查询所有用户信息")
    @GetMapping("/test")
    public Result Test() {
        return Result.ok("齐菁菁");
    }
    @ApiOperation("删除用户信息")
    @PostMapping("/deleteById")
    public Result deleteUserById(@RequestBody @Validated User user) {
        int result = userService.deleteUserMessageById(user.getId());
        if (result > 0) {
            return Result.ok(ResultCodeEnum.SUCCESS);
        }
        return Result.fail(ResultCodeEnum.FAIL);
    }

    @ApiOperation("新增/编辑用户信息")
    @PostMapping("/insertOrUpdate")
    public Result insertOrUpdate(@RequestBody @Validated User user) {
        int result = userService.insertOrUpdateUserMessage(user);
        if (result > 0) {
            return Result.ok(ResultCodeEnum.SUCCESS);
        }
        return Result.fail(ResultCodeEnum.FAIL);
    }

    @ApiOperation("批量删除用户信息")
    @PostMapping("/deleteByIds")
    public Result deleteUsersByIds(@RequestBody List<String> ids) {
        int result = userService.deleteUserMessageByIds(ids);
        if (result > 0) {
            return Result.ok(ResultCodeEnum.SUCCESS);
        }
        return Result.fail(ResultCodeEnum.FAIL);
    }

    @GetMapping("/export")
    public void export(HttpServletResponse response) throws IOException {
        List<UserExport> userList = userService.getAllUsers(); // 获取用户列表

        // 设置响应头信息
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("用户信息", "UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xls");
        // 使用Hutool的ExcelUtil工具类将数据写入Excel文件并将其发送到客户端
        ExcelWriter writer = ExcelUtil.getWriter();
        writer.addHeaderAlias("id", "ID");
        writer.addHeaderAlias("username", "姓名");
        writer.addHeaderAlias("nickname", "昵称");
        writer.addHeaderAlias("email", "邮箱");
        writer.addHeaderAlias("phone", "电话");
        writer.addHeaderAlias("address", "地址");
        writer.addHeaderAlias("avatarUrl", "头像");
        writer.addHeaderAlias("createTime", "创建时间");
        writer.write(userList, true);
        writer.flush(response.getOutputStream());
        writer.close();
    }
    @PostMapping("/import")
    public Result importData(@RequestParam("file") MultipartFile file) throws IOException {
        InputStream inputStream = file.getInputStream();
        // 读取 Excel 表格的第一行，获取所有表头
        List<Object> headers = ExcelUtil.getReader(inputStream).readRow(0);
        HashMap<String, String> map = Maps.newHashMap();
        for (Object header : headers) {
            if (header.equals("姓名")) {
                map.put((String) header, "username");
            } else if (header.equals("昵称")) {
                map.put((String) header, "nickname");
            } else if (header.equals("邮箱")) {
                map.put((String) header, "email");
                // 其他列的映射关系
            } else if (header.equals("电话")) {
                map.put((String) header, "phone");
                // 其他列的映射关系
            } else if (header.equals("地址")) {
                map.put((String) header, "address");
                // 其他列的映射关系
            } else if (header.equals("头像")) {
                map.put((String) header, "avatarUrl");
                // 其他列的映射关系
            }
        }
        // 关闭之前的输入流并重新打开一个新的输入流
        inputStream.close();
        inputStream = file.getInputStream();
        try (InputStream newInputStream = inputStream) {
            // 使用 Hutool 的 ExcelUtil 读取数据，并指定列名映射关系
            List<User> userList = ExcelUtil.getReader(newInputStream)
                    .setHeaderAlias(map)
                    .readAll(User.class);
            // 将数据保存到数据库
            userService.saveAll(userList);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();    // 关闭输入流
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.ok();
    }
}
